const createStore = (reducer) => {
  let state;
  let listeners = [];

  const getState = () => state;

  const dispatch = (action) => {
    //判断 action 是否为函数
    if (typeof action === 'function') {
      return action(dispatch, getState);
    }

    state = reducer(state, action);
    listeners.forEach((listener) => listener());
  };

  const subscribe = (listener) => {
    listeners.push(listener);

    return () => {
      listeners = listeners.filter((l) => l !== listener);
    };
  };

  dispatch({}); // 初始化 state

  return {
    getState,
    dispatch,
    subscribe,
  };
};